<!-- 首页 -->

<template>
	<view class="home pageBg">
		<custom-navbar title="素材星球"></custom-navbar>
		<view class="banner clipCircleIn">
			<swiper autoplay indicator-dots indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#fff"
				circular interval="3000">

				<swiper-item v-for="(item,pId) in pageData.bannerList" :key="item.pId">
					<image :src='item.imgUrl' mode="aspectFill"></image>
				</swiper-item>
			</swiper>
		</view>
		<view class="notice">
			<view class="left">
				<uni-icons type='sound-filled' size='20'></uni-icons>
				<text class='text'>公告</text>
			</view>
			<view class="center">
				<swiper autoplay vertical interval="1500" duration="300" circular class="swiper-center">
					<swiper-item v-for='(item,nId) in pageData.noticeList' :key="item.nId" class='swiper-center-item'
						@click="handleItemClick(item.nId)">
						<text>{{item.title}}</text>
					</swiper-item>
				</swiper>
			</view>
			<view class="right">
				<uni-icons type='fire-filled' size='20' color="#28b389"></uni-icons>
			</view>
		</view>
		<view class="select">
			<common-title>
				<template #name>
					<uni-section title="每日推荐" type="line" titleFontSize="18px"></uni-section>
				</template>
				<template #default>
					<view class="material-type">
						<uni-segmented-control class="segment" :current="segmentData.current"
							:values="segmentData.items" @clickItem="onClickItem" styleType="text"
							:activeColor="segmentData.activeColor"></uni-segmented-control>

					</view>
				</template>
				<template #custom>
					<view class="date">
						<uni-icons type='calendar' size='18'></uni-icons>
						<view class="text">
							<uni-dateformat :date="Date.now()" format="MM-dd"></uni-dateformat>
						</view>
					</view>

				</template>
			</common-title>
			<view class="conent">
				<scroll-view scroll-x>
					<view v-if="segmentData.current === 0" class="box"
						v-for=" (item,index) in pageData.dailyRecommendationList" :key="item.materialId">
						<image :src="item.thumbnailUrl" mode="aspectFill" @click="goView(item)" lazy-load webp>
						</image>
					</view>
					<view v-if="segmentData.current === 1" class="box"
						v-for=" item in pageData.dailyRecommendationList">
						<image :src="item.thumbnailUrl" mode="aspectFill" @click="goView(item)" lazy-load webp>
						</image>
					</view>
					<view v-if="segmentData.current === 2" class="box"
						v-for=" item in pageData.dailyRecommendationList">
						<image :src="item.thumbnailUrl" mode="aspectFill" @click="goView(item)" lazy-load webp>
						</image>
					</view>
				</scroll-view>
			</view>
		</view>
		<view class="theme">
			<common-title>
				<template #name>
					<uni-section title="专题精选" type="line" titleFontSize="18px"></uni-section>
				</template>
				<template #custom>
					<navigator url="/pages/classify/classify" class="more" open-type="switchTab">
						More
					</navigator>
				</template>
			</common-title>
			<view class="conent">
				<theme-item v-for="(item,index) in pageData.topicList" :key="item.pdId" :item="item"></theme-item>

				<theme-item :isMore="true"></theme-item>
			</view>
		</view>
		<uni-popup ref="noticePopup">
			<view class="Popup">
				<view class="popHeader">
					<view class="">

					</view>
					<view class="title">公告</view>
					<view class="close" @click="closePage">
						<uni-icons type="closeempty" size="20" color="#999"></uni-icons>
					</view>
				</view>
				<view class="content">
					<text class="noticeTitle">{{noticeInfo.title}}</text>
					<text class="Popup-text-2">{{noticeInfo.content}}</text>
					<!-- <text class="Popup-text-3">位置：我的-联系客服 </text> -->
				</view>
				<view class="footer">
					<button type="default" size="mini" plain @click="confirm"> 确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		getMpList,
		getMpNotice,
		getTopicList
	} from "@/api/page.js"
	import {
		ref,
		computed,
		onMounted,
		reactive,
		toRefs
	} from "vue";
	import {
		onLoad,
		onReady,
		// onPageScroll,
		onShow,
		// onReachBottom
		onShareAppMessage,
		onShareTimeline
	} from "@dcloudio/uni-app";
	import {
		useUserInfoStore,
	} from "@/stores/modules/user.js"
	import {
		loginByWeChat
	} from "@/api/user.js"
	import {
		generateTimestamp,
		isTimestampExpired
	} from "@/utils/common.js"
	import {
		getDailyRecommendationList
	} from "@/api/page.js"

	const userLoginInfo = useUserInfoStore();

	// 公告栏弹窗ref
	const noticePopup = ref(null);
	// 公告栏信息ref
	const noticeInfo = ref({
		title: '',
		content: ''
	})

	// 页面数据
	const pageData = reactive({
		bannerList: [{
				pId: "23690210766",
				remark: null,
				state: 0,
				delFlag: 0,
				updateBy: "hiyori",
				updateTime: "2025-01-27 16:53:07",
				imgUrl: "https://z-mytest.oss-cn-beijing.aliyuncs.com/creative/6fb0d601-9f3c-404e-897a-4daa62f95f67.png"
			},
			{
				pId: "3",
				remark: null,
				state: 0,
				delFlag: 0,
				updateBy: "hiyori",
				updateTime: "2025-01-23 01:21:36",
				imgUrl: "https://z-mytest.oss-cn-beijing.aliyuncs.com/creative/1397434a-bfeb-46ec-85bf-18d9fe4dace3.jpg"
			}
		],
		topicList: [{
				coverText: "游戏",
				coverImg: "https://z-mytest.oss-cn-beijing.aliyuncs.com/creative/872cb5f0-43d4-43e5-8c2c-49facb8cec66.png",
				updateTime: "2025-02-07 17:53:33"
			},
			{
				coverText: "图书",
				coverImg: "https://z-mytest.oss-cn-beijing.aliyuncs.com/creative/d7c86379-a169-47e8-b6a7-9e9e4b06f6aa.jpg",
				updateTime: "2025-02-07 17:53:33"
			},
			{
				coverText: "动漫",
				coverImg: 'https://z-mytest.oss-cn-beijing.aliyuncs.com/creative/fc6c7050-0be6-4bb1-a241-fe91b171ff74.png',
				updateTime: "2025-02-07 17:53:33"
			},
			{
				coverText: '景色',
				coverImg: "https://z-mytest.oss-cn-beijing.aliyuncs.com/creative/ed8e4a5a-b18b-4338-af76-7940d77fd7c3.jpg",
				updateTime: "2025-02-07 17:53:33"
			},

		],
		noticeList: [{
			nId: "1",
			title: "公告标题",
			content: "公告内容",
			img: null,
			state: 0,
			delFlag: 0,
			createBy: "hiyori",
			createTime: "2025-01-16 14:11:27",
			updateBy: "hiyori",
			updateTime: "2025-01-16 14:11:27",
			remark: null
		}],
		dailyRecommendationList: [{
				thumbnailUrl: "https://z-mytest.oss-cn-beijing.aliyuncs.com/creative/6fb0d601-9f3c-404e-897a-4daa62f95f67.png",
				typeName: "美女",
				materialUrl: [
					"https: //z-mytest.oss-cn-beijing.aliyuncs.com/creative/0cb088c3-824f-4e71-a46c-36db344402a6.mp4"
				],
				typeName: "动漫",
				materialId: "04934",
				updateTime: "2025-02-07 17:53:33"

			},
			{
				thumbnailUrl: "https://z-mytest.oss-cn-beijing.aliyuncs.com/creative/6fb0d601-9f3c-404e-897a-4daa62f95f67.png",
				typeName: "美女",
				materialUrl: [
					"https: //z-mytest.oss-cn-beijing.aliyuncs.com/creative/0cb088c3-824f-4e71-a46c-36db344402a6.mp4"
				],
				typeName: "动漫",
				materialId: "04934",
				updateTime: "2025-02-07 17:53:33"
			}
		]
	})

	// 每日推荐分段器的数据
	const segmentData = reactive({
		items: ['图片', '音频', '视频'],
		current: 0,
		activeColor: "#007aff",

	})

	// onReady
	onReady(() => {
		// 获取用户的登录信息 是否有登录缓存信息
		if (uni.getStorageSync('isLogin')) {

			// 如果登陆时间差大于2h
			if (isTimestampExpired(uni.getStorageSync("loginTime"))) {
				//进行静默登录
				// 登录，先检查当前用户是否已经注册过
				uni.login({
					"provider": "weixin",
					"onlyAuthorize": true, // 微信登录仅请求授权认证
					success: function(event) {
						const {
							code
						} = event
						//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
						loginByWeChat(event.code).then((res) => {
							if (res.code == 200) {
								// 将返回用户信息保存到store中
								userLoginInfo.saveUserInfo(res.data);

								// 设置登陆状态
								uni.setStorageSync("isLogin", true)
								// 更新缓存的用户信息
								uni.setStorageSync("userInfo", res.data)

								// 更新用户登录的时间戳
								uni.setStorageSync("loginTime", generateTimestamp())
							}
						})

					},
					fail: function(err) {
						// 登录授权失败
						// err.code是错误码  弹窗显示失败
					}
				})

			} else {
				// 如果登陆时间差小于2h，则直接从缓存中获取用户信息
				userLoginInfo.saveUserInfo(uni.getStorageSync("userInfo"))
			}

		} else {
			// 无用户缓存信息
		}
		// 获取每日推荐的素材
		getDailyRecommendation(0)

	})
	// 分享给好友
	onShareAppMessage(() => {
		return {
			title: '来看看吧！',
			path: '/pages/index/index',
			imageUrl: 'https://z-mytest.oss-cn-beijing.aliyuncs.com/creative/cg_sz08_0305.png'
		}
	})

	// 分享到朋友圈
	// onShareTimeline(() => {
	// 	return {
	// 		title: '来看看吧！',
	// 		imageUrl: 'https://z-mytest.oss-cn-beijing.aliyuncs.com/creative/cg_sz08_0305.png'
	// 	}
	// })

	// onShow 可以在TabBar切换时，重新执行
	onShow(() => {
		// 获取Banner部分的数据
		getBannerData()
		// 获取公告栏消息
		getNotice()
		// 获取专题精选的数据
		getTopicData()

		getDailyRecommendation(0)
	})

	// 获取每日推荐的数据
	const getDailyRecommendation = async (Index) => {
		await getDailyRecommendationList(Index)
			.then((res) => {
				if (res.code == 200) {
					pageData.dailyRecommendationList = res.data
					// console.log("dailyRecommendationList", pageData.dailyRecommendationList);
				}
			})
	}

	// 获取Banner区域数据 
	const getBannerData = async () => {
		await getMpList()
			.then((res) => {
				if (res.code == 200) {
					// console.log('返回轮播图Data:', res);
					pageData.bannerList = res.data
				}
			}).catch((err) => {
				// throw new error("网络异常！")
				uni.showToast({
					title: "获取数据异常",
					icon: "error",
				})
			});
	}

	// 获取公告栏消息
	const getNotice = async () => {
		await getMpNotice()
			.then((res) => {
				// console.log('返回公告栏Data:', res);
				pageData.noticeList = res.data
			})
			.catch((err) => {
				// throw new error("网络异常！")
				uni.showToast({
					title: "获取数据异常",
					icon: "error",
				})
			});
	}

	// 获取专题精选的数据
	const getTopicData = async () => {
		await getTopicList()
			.then((res) => {
				if (res.code == 200) {
					pageData.topicList = res.data
					// console.log("topicList", pageData.topicList);
				}
			}).catch((err) => {
				// throw new error("网络异常！")
				uni.showToast({
					title: "获取数据异常",
					icon: "error",
				})
			});
	}

	const goView = (data) => {
		// 将数据加入缓存，进行json.Stringify() 节省空间
		uni.setStorageSync("materialInfo", JSON.stringify(data))
		uni.navigateTo({
			url: '/pages/preview/preview',
		})
	}

	// 打开公告栏
	const handleItemClick = (nId) => {
		// console.log("nId:", nId);
		// 获取点击的公告详情
		pageData.noticeList.map((item) => {
			if (item.nId == nId) {
				console.log('item', item);
				noticeInfo.value = item
			}
		})
		// 打开公告弹窗
		noticePopup.value.open()
	}

	const confirm = () => {
		noticePopup.value.close()
	}
	const closePage = () => {
		noticePopup.value.close()
	}

	// 每日推荐分段器的点击事件
	const onClickItem = (e) => {
		segmentData.current = e.currentIndex
		console.log('当前点击的索引：', e.currentIndex);
		// 调用获取每日推荐的数据
		getDailyRecommendation(e.currentIndex)
	}
</script>

<style lang="scss" scoped>
	.home {
		position: relative;

		.banner {
			width: 750rpx;
			padding: 30rpx 0;
			/* #ifdef H5 */
			animation-duration: 1s;
			animation-fill-mode: both;
			/* #endif */


			swiper {
				width: 750rpx;
				height: 340rpx;

				// & 相当于 swiper
				&-item {
					width: 100%;
					height: 100%;
					padding: 0 30rpx;

					image {
						width: 100%;
						height: 100%;
						border-radius: 10rpx;
					}
				}
			}
		}

		/* #ifdef H5 */
		@keyframes clipCircleIn {
			0% {
				clip-path: circle(0 at 50% 50%);
			}

			100% {
				clip-path: circle(100% at 50% 50%);
			}
		}

		.clipCircleIn {
			animation-name: clipCircleIn;
		}

		/* #endif */


		.notice {
			width: 690rpx;
			height: 80rpx;
			background: #f9f9f9;
			line-height: 80rpx;
			margin: 0 auto;
			border-radius: 80rpx;
			display: flex;

			.left {
				width: 140rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				:deep() {
					.uni-icons {
						color: $brand-theme-color !important;
					}
				}

				.text {
					color: $text-font-color-1;
					// 文本加粗
					font-weight: 600;
					font-size: 28rpx;
				}
			}

			.center {
				flex: 1;

				swiper {
					height: 100%;

					&-item {
						height: 100%;
						font-size: 30rpx;
						color: #666;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
					}
				}
			}

			.right {
				width: 70rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}

		.select {

			.material-type {
				display: block;
				width: 250rpx;
				height: 30rpx;
				position: relative;

				.segment {
					position: relative;
					top: -25rpx;

				}
			}

			.date {
				color: $brand-theme-color;
				display: flex;
				align-items: center;

				:deep() {
					.uni-icons {
						color: $brand-theme-color !important;
					}
				}

				.text {
					margin-left: 5rpx;
				}
			}

			.conent {
				width: 720rpx;
				margin-left: 30rpx;

				scroll-view {
					white-space: nowrap;

					.box {
						width: 200rpx;
						height: 430rpx;
						display: inline-block;
						margin-right: 15rpx;

						image {
							width: 100%;
							height: 100%;
							border-radius: 12rpx;
						}

					}

					.box:last-child {
						margin-right: 30rpx;
					}
				}
			}
		}

		.theme {
			padding: 10rpx 0;

			.more {
				font-size: 32rpx;
				color: #888;
			}

			.conent {
				padding: 0 30rpx;
				display: grid;
				gap: 15rpx;
				grid-template-columns: repeat(3, 1fr);
			}
		}



		.Popup {
			background: #fff;
			padding: 30rpx;
			width: 70vw;
			border-radius: 30rpx;

			.popHeader {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.title {
					color: $text-font-color-2;
					font-size: 35rpx;
					font-weight: 600;
				}

				.close {
					padding: 6rpx;
				}
			}

			.content {
				padding: 30rpx 0;
				display: column;
				justify-content: center;
				align-items: center;
				gap: 20rpx;

				.text {

					padding-left: 10rpx;
					width: 80rpx;
					line-height: 1em;
					text-align: right;
				}

				.noticeTitle {}

				.Popup-text-2 {
					color: #FFCA3E;
					font-size: 25rpx;
					display: block;
					margin-top: 15rpx;

				}

				.Popup-text-3 {
					color: red;
					font-size: 30rpx;
					display: block;
					margin-top: 15rpx;
				}
			}

			.footer {
				display: flex;
				padding: 10rpx 0;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>